import { createRouter, createWebHashHistory } from 'vue-router';
import Login from './components/MyLogin.vue';
import Home from './components/MyHome.vue';
import Goods from './components/menus/MyGoods.vue';
import Orders from './components/menus/MyOrders.vue';
import Settings from './components/menus/MySettings.vue';
import Rights from './components/menus/MyRights.vue';
import Users from './components/menus/MyUsers.vue';

import UserDetail from './components/user/MyUserDetail.vue';

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    { path: '/', redirect: 'login' },
    { path: '/login', component: Login, name: 'login' },
    {
      path: '/home',
      redirect: '/home/users',
      component: Home,
      name: 'home',
      children: [
        { path: 'goods', component: Goods, name: 'goods' },
        { path: 'orders', component: Orders, name: 'orders' },
        { path: 'settings', component: Settings, name: 'settings' },
        { path: 'users', component: Users, name: 'users' },
        { path: 'rights', component: Rights, name: 'rights' },
        { path: 'users/:id', component: UserDetail, name: 'userdetail', props: true },
      ],
    },
  ],
});

router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next();
  const token = localStorage.getItem('token');
  if (!token) {
    return next('/login');
  }
  next();
});
export default router;
